<template>
  <div class="app-container">
    <div style="margin-left: 3%; margin-top: 3%">
      <el-upload
        class="avatar-uploader"
        action=""
        :show-file-list="false"
        :http-request="uploadAvatar"
        :before-upload="beforeUploadAvatar"
      >
        <img v-if="user.avatar" :src="user.avatar" style="border-radius: 50%; width: 200px; height: 200px" class="avatar">
        <i v-else class="el-icon-plus avatar-uploader-icon" />
      </el-upload>
      <div style="margin-left: 4%; margin-top: 30px">
        <h3>登陆：{{ user.username }}</h3>
        <h3>姓名：{{ user.name }}</h3>
      </div>
      <div style="width: 17%"><el-divider /></div>
      <div style="margin-left: 4%; margin-top: 30px">
        <h3>密码：<uPass :id="id" /></h3>
      </div>
      <div style="width: 17%"><el-divider /></div>
    </div>
  </div>
</template>

<script>
import waves from '@/directive/waves/waves'
import { mapGetters } from 'vuex'
import { uploadUserAvatar } from '@/api/user'
import { UserInfoImage } from '@/api/user'
import uPass from './components/uPass'

export default {
  directives: { waves },
  components: { uPass },
  data() {
    return {
      user: {},
      formData: {}
    }
  },
  computed: {
    ...mapGetters([
      'id',
      'name',
      'username',
      'avatar'
    ])
  },
  created() {
    this.getUser()
  },
  methods: {
    getUser() {
      this.user = {
        id: this.id,
        name: this.name,
        username: this.username,
        avatar: this.avatar
      }
    },
    // 选择头像后点击确定后触发的事件
    beforeUploadAvatar(file) {
      const isLt2M = file.size / 1024 / 1024 < 10

      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 10MB!')
      }
      return isLt2M
    },
    uploadAvatar(file) {
      // 定义一个FormData类
      const AvatarFile = new FormData()
      // 把照片传进去
      AvatarFile.append('avatar', file.file)
      // 发起请求
      uploadUserAvatar(AvatarFile).then((res) => {
        UserInfoImage(this.user.id, { name: res.data.name }).then((resInfo) => {
          this.user.avatar = process.env.VUE_APP_BASE_API + resInfo.data.name
          this.$notify.success({
            type: 'success',
            title: '成功',
            message: resInfo.message,
            showClose: true,
            duration: 5 * 1000
          })
        })
      })
    }
  }
}
</script>

<style scoped>

</style>
